package europe

import (
	"match-spider/util/boltdb"
	"github.com/boltdb/bolt"
	"fmt"
	"strings"
	"github.com/gocolly/colly"
	"match-spider/util/queue"
	"github.com/robertkrimen/otto"

	"encoding/json"
	"time"
	"math/rand"
	"reflect"
)

/**
易胜博(安提瓜和巴布达)		66676027
伟德(直布罗陀)	66647121
威廉希尔(英国)	66672565
明陞(菲律宾)		66672648
利记sbobet(英国)	66672646
立博(英国)	66673844
金宝博(马恩岛)	66676033
SB	66676031
Interwetten(塞浦路斯)		66656820
bet 365(英国)	66570177
竞彩官方
澳门
Oddset(德国)
SNAI(意大利)
香港马会(中国香港)
 */

var failedEurope=false
var failedTimesEurope=1
func europeSpider(bucket string,id string,isRepeat bool)  {
	url:="http://1x2.nowscore.com/" +id + ".js"

	c := colly.NewCollector()
	c.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36"
	c.OnResponse(func(response *colly.Response) {

		content:=string(response.Body)

		if strings.Compare(strings.TrimSpace(content),"")==0{
			//请求失败
			queue.EnqueueString("./data_schedule/europe",bucket+"^"+id)
			failedEurope=true
			if isRepeat{
				failedTimesEurope++
			}

		}else{
			vm := otto.New()
			vm.Run(content)
			game,_:=vm.Get("game")
			gameDetail,_:=vm.Get("gameDetail")
			gameValue,_:=game.Export()
			gameDetailValue,_:=gameDetail.Export()
			t:=reflect.TypeOf(gameValue)
			if strings.Compare(t.String(),"[]interface {}")==0{
				return
			}

			gameSlice:=make([]string,0)
			for _,v:=range gameValue.([]string) {

				if strings.Contains(v,"易胜博(安提瓜和巴布达)")||
					strings.Contains(v,"伟德(直布罗陀)")||
					strings.Contains(v,"威廉希尔(英国)")||
					strings.Contains(v,"明陞(菲律宾)")||
					strings.Contains(v,"利记sbobet(英国)")||
					strings.Contains(v,"立博(英国)")||
					strings.Contains(v,"金宝博(马恩岛)")||
					strings.Contains(v,"SB")||
					strings.Contains(v,"Interwetten(塞浦路斯)")||
					strings.Contains(v,"bet 365(英国)")||
					strings.Contains(v,"竞彩官方")||
					strings.Contains(v,"澳门")||
					strings.Contains(v,"Oddset(德国)")||
					strings.Contains(v,"SNAI(意大利)")||
					strings.Contains(v,"香港马会(中国香港)"){
					gameSlice=append(gameSlice, v)
				}

			}


			gameJson,_:=json.Marshal(gameSlice)

			gameDetailJson,_:=json.Marshal(gameDetailValue)

			boltdb.Put("europe",bucket,id,string(gameJson))
			boltdb.Put("europe-detail",bucket,id,string(gameDetailJson))
		}
	})

	// Before making a request print "Visiting ..."
	c.OnRequest(func(r *colly.Request) {
		fmt.Println("Visiting", r.URL.String())
	})
	c.OnError(func(r *colly.Response, err error) {
		fmt.Println("Error Request URL:", r.Request.URL)
		queue.EnqueueString("./data_schedule/europe",id)
		failedEurope=true
		if isRepeat{
			failedTimesEurope++
		}
	})

	c.Visit(url)
}
/**
欧赔
 */
func europeFailProcess(){
	if failedEurope{
		//休眠
		time.Sleep(time.Minute*time.Duration(3*failedTimesEurope))
	}
	data:=queue.Dequeue("./data_schedule/europe")

	if data==nil{
		return
	}
	failedEurope=false
	s:=strings.Split(string(data.Value),"^")

	if(len(s)<2){
		europeFailProcess()
		return
	}
	europeSpider(s[0],s[1],true)
	seed:=200+rand.Intn(300)
	time.Sleep(time.Millisecond*time.Duration(seed))
	europeFailProcess()
}
func Fetch()  {
	//1338973
	//europeSpider("000","1247837",false)
	//return

	boltdb.ScanTx("matchs", func(tx *bolt.Tx) {

		tx.ForEach(func(name []byte, b *bolt.Bucket) error {

			b.ForEach(func(k, v []byte) error {
				value:=string(v)
				s:=strings.Split(value,"^")

				asiaOdds:=strings.TrimSpace(s[7])
				underOverOdds:=strings.TrimSpace(s[8])
				if asiaOdds!=""&&underOverOdds!=""{
					//抓取

					league:=strings.TrimSpace(s[1])
					europeSpider(league,string(k),false)
					if failedEurope{
						failedEurope=false
						time.Sleep(time.Second*90)
					}else{
						seed:=200+rand.Intn(300)
						time.Sleep(time.Millisecond*time.Duration(seed))
					}

				}
				return nil
			})
			return nil
		})

	})

	fmt.Println("================= queue begin =================")
	//处理失败记录
	europeFailProcess()
}
